

from whiff import resolver
from whiff import whiffenv
from whiff.middleware import misc

class cgiRewrite(misc.utility):
    def __init__(self,
                 parameterName,
                 handler='_ChildTemplate/'
                 ):
        self.parameterName = parameterName
        self.handler = handler
    def __call__(self, env, start_response):
        path_remainder = env[whiffenv.PATH_REMAINDER]
        operation = ""
        remainder = []
        if path_remainder:
            operation = path_remainder[0]
            remainder = path_remainder[1:]
        parameterName = self.param_value(self.parameterName, env)
        handler = self.param_value(self.handler, env)
        # modify the cgi dictionary to include the user, date and title parameters
        env = resolver.process_cgi(env, parse_cgi=True)
        cgi_dict = env[whiffenv.CGI_DICTIONARY].copy()
        cgi_dict[parameterName] = [operation]
        env[whiffenv.CGI_DICTIONARY] = cgi_dict
        # delegate the response to blog_root/OPERATION
        url = handler + "/".join(remainder)
        relative_url = env[whiffenv.RESPONDING_PATH] + ["dummy"]
        #pr "relative_url", relative_url
        #pr "url", url
        return resolver.callUrl(url, env, start_response, relative_url)

__middleware__ = cgiRewrite
